package com.itheima.auth.config;

import com.itheima.common.utils.RSAKeyCreateUtils;
import com.itheima.common.utils.RsaUtils;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.context.properties.ConfigurationProperties;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Properties;

@Getter
@Setter
@ConfigurationProperties(prefix = "rsa.key")
public class RsaKeyProperties {
    private String pubKeyPath;
    private String priKeyPath;

    private PublicKey publicKey;
    private PrivateKey privateKey;

    @SneakyThrows
    @PostConstruct //使用这个注解表明在构建对象完成之后创建这两个对象
    public void createRsaKey(){
        File pubKeyFile = new File(pubKeyPath);
        File priKeyFile = new File(priKeyPath);

        if (!pubKeyFile.exists() || !priKeyFile.exists()) {
            String[] paths = RSAKeyCreateUtils.createDefaultRsaKeyFile();
            pubKeyPath = paths[0];
            priKeyPath = paths[1];
        }
        publicKey = RsaUtils.getPublicKey(pubKeyPath);
        privateKey = RsaUtils.getPrivateKey(priKeyPath);
    }
}
